#include "ping_service.h"
#include "framework/service_factory.h"
#include <chrono>
#include <sstream>
namespace cpp_backend
{
    namespace services
    {
        PingService::PingService() : ServiceBase("ping_service", "1.0.0"),
                                     start_time_(std::chrono::system_clock::now())
        {
        }
        bool PingService::Initialize()
        {
            request_count_ = 0;
            ping_count_ = 0;
            echo_count_ = 0;

            start_time_ = std::chrono::system_clock::now();
            return ServiceBase::Initialize();
        }
        bool PingService::Start()
        {
            if (!ServiceBase::Start())
            {
                return false;
            }
            // TODO 订阅一些事件
            return true;
        }
        void PingService::Stop()
        {
            ServiceBase::Stop();
        }
        bool PingService::HealthCheck()
        {
            return ServiceBase::HealthCheck();
        }
        std::string PingService::GetServicedescription() const
        {
            return "Ping service for testing framework functioanality";
        }
        framework::Response PingService::HandleRequest(const framework::Request &request)
        {
            request_count_++;
            const std::string &path = request.GetPath();
            const std::string &method = request.GetMethod();
            if (path == "/api/ping")
            {
                return HandlePing(request);
            }
            else if (path == "/api/echo")
            {
                return HandleEcho(request);
            }
            else if (path == "/api/info")
            {
                return HandleInfo(request);
            }
            else
            {
                return framework::Response::Error(framework::ErrorCode::SERVICE_NOT_FOUND, std::string("Path not found") + path);
            }
        }
        framework::Response PingService::HandlePing(const framework::Request &request)
        {
            ping_count_++;
            nlohmann::json data;
            data["message"] = "Pong";
            data["timestamp"] = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::system_clock::now().time_since_epoch()).count();
            data["service"] = GetServiceName();
            data["version"] = GetServiceVersion();
            return framework::Response::Success(data);
        }
        framework::Response PingService::HandleEcho(const framework::Request &request)
        {
            echo_count_++;
            nlohmann::json data;
            if (request.GetMethod() == "POST")
            {
                data["echo"] = request.GetBody();
            }
            else
            {
                const auto &params = request.GetParams();
                if (!params.empty())
                {
                    nlohmann::json params_json;
                    for (const auto &param : params)
                    {
                        params_json[param.first] = param.second;
                    }
                    data["echo"] = params_json;
                }
                else
                {
                    data["echo"] = "老婆我爱你";
                }
            }
            data["method"] = request.GetMethod();
            data["path"] = request.GetPath();
            data["timestamp"] = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::system_clock::now().time_since_epoch()).count();
            return framework::Response::Success(data);
        }
        framework::Response PingService::HandleInfo(const framework::Request &request)
        {
            nlohmann::json data;
            // 基本服务信息
            data["service_name"] = GetServiceName();
            data["service_version"] = GetServiceVersion();
            data["service_description"] = GetServicedescription();
            data["is_running"] = IsRunning();
            data["health_check"] = HealthCheck();
            // 运行时间
            auto now = std::chrono::system_clock::now();
            auto uptime_seconds = std::chrono::duration_cast<std::chrono::seconds>(now - start_time_).count();
            data["uptime_seconds"] = uptime_seconds;
            // 统计信息
            data["statistics"] = {
                {"total_requests", request_count_.load()},
                {"ping_requests", ping_count_.load()},
                {"echo_requests", echo_count_.load()}

            };
            // 请求信息
            data["request_info"] = {
                {"method", request.GetMethod()},
                {"path", request.GetPath()},
                {"client_ip", request.GetClientIp()},
                {"user_id", request.GetUserId()},
                {"request_id", request.GetRequestId()}};
            return framework::Response::Success(data);
        }
    }
}
// 自动注册服务（微服务架构中不需要，已注释）
// REGISTER_SERVICE(PingService, "ping_service")